<?php

/**
 * Class for handling all kinds of user-related administration, such as:
 * login, registration, authentication, validation, and role management.
 * @author Edgar Drake
 */
class User extends CI_Controller {
    
    public function __construct() {
        global $userdb, $itemdb;
        parent::__construct();

        // Database Connection
        $connection = new Mongo('localhost:27017'); // Connect to Mongo
        $db = $connection->rpp; // Select a database
        $userdb = $db->user; // Select a collection
        $itemdb = $db->item;
    }
    
// <editor-fold defaultstate="collapsed" desc="Region: Web Service">
    /**
     * Web service for log-in authentication.
     * @global type $user Database collection of user.
     */
    public function auth() {
        global $userdb;
        $username = $_POST["username"];
        $password = $_POST["password"];
        $user     = $userdb->findOne(array("_id" => $username, "password" => md5($password)));

        if ($user != null) {
            // TO-DO
            echo "login success:" . $user['sesstoken'];
        } else {
            // TO-DO ERROR
            echo "login error";
        }
    }

    /**
     * 
     * @global type $user
     */
    public function createUser() {
        global $userdb;
        $username = $_POST['username'];
        $password = $_POST['password'];
        $name     = $_POST['name'];
        $lookup   = strtolower($_POST['name']);
        $email    = $_POST['email'];
        
        // Check whether the username is available
        if ($userdb->findOne(array("_id" => $username)) != null) {
            // User already exist
            echo "username exist";
        } else {
            // User is not exist. Set up data
            $userdata = array(
                "_id"       => $username,
                "password"  => md5($password),
                "name"      => $name,
                "lookup"    => $lookup,
                "email"     => $email,
                "sesstoken" => md5(substr($username, -4) + substr($password, -4))
            );
            // Write to DB
            $userdb->insert($userdata);
            echo "register success";
        }
    }
    
    /**
     * Return all data of approriate user.
     * @param type $userid
     */
    public function profile($username) {
        global $userdb, $itemdb;
        if ($username !== "") {
            $user = $userdb->findOne(array("_id" => $username));
            $item_cursor = $itemdb->find(array("author" => $username));
            foreach ($item_cursor as $cursor) {
                $items[] = $cursor;
            }
            $user["items"] = $items;
            echo json_encode($user);
        } else {
            echo "user not found";
        }
    }
    
    public function search($query) {
        global $userdb;
        $query = strtolower($query);
        $format = array("name" => true);
        $paramOR = array(
            '$or' => array(
                array("lookup"=> new MongoRegex("/".$query."/")),
                array("_id"   => new MongoRegex("/".$query."/"))
            )
        );
        $user_cursor = $userdb->find($paramOR, $format);
        foreach ($user_cursor as $cursor) {
            $users[] = $cursor;
        }
        echo json_encode($users);
    }

// </editor-fold>
        
// <editor-fold defaultstate="collapsed" desc="Region: WebApp Renderer">
    
    /**
     * Render a view page of login
     * @param type $status ok: no problem, mismatch: username/password mismatch
     */
    public function login($status = "ok") {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', NULL, 'required');
        $this->form_validation->set_rules('password', NULL, 'required');
        
        if ($this->form_validation->run() === FALSE) {
            $data["status"] = $status;
            $this->load->view('d-login', $data);
        } else {
            $this->auth();
        }
    }

    /**
     * Render a view page of registration
     * @param type $status ok: no problem, exist: username already used, mismatch: password/e-mail with confirm mismatch
     */
    public function register($status = "ok") {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', NULL, 'required');
        $this->form_validation->set_rules('name', NULL, 'required');
        $this->form_validation->set_rules('password', NULL, 'required|matches[cpassword]|min_length[8]');
        $this->form_validation->set_rules('cpassword', NULL, 'required|matches[password]');
        $this->form_validation->set_rules('email', NULL, 'required|matches[cemail]');
        $this->form_validation->set_rules('cemail', NULL, 'required|matches[email]');

        if ($this->form_validation->run() === FALSE) {
            $data["status"] = $status;
            $this->load->view('d-register', $data);
        } else {
            $this->createUser();
        }
    }

// </editor-fold>
    
}

?>
